Ext.control.MapField = Ext.extend(Ext.form.TriggerField,  {
    
/**
     * @cfg {String} format
     * The default date format string which can be overriden for localization support.  The format must be
     * valid according to {@link Date#parseDate} (defaults to 'm/d/Y').
     */
    format : "m/d/Y",
    
/**
     * @cfg {String} altFormats
     * Multiple date formats separated by "|" to try when parsing a user input value and it
     * does not match the defined format (defaults to
     * 'm/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d').
     */
    altFormats : "m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d",
    
/**
     * @cfg {String} disabledDaysText
     * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
     */
    disabledDaysText : "Disabled",
    
/**
     * @cfg {String} disabledDatesText
     * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
     */
    disabledDatesText : "Disabled",
    
/**
     * @cfg {String} minText
     * The error text to display when the date in the cell is before {@link #minValue} (defaults to
     * 'The date in this field must be after {minValue}').
     */
    minText : "The date in this field must be equal to or after {0}",
    
/**
     * @cfg {String} maxText
     * The error text to display when the date in the cell is after {@link #maxValue} (defaults to
     * 'The date in this field must be before {maxValue}').
     */
    maxText : "The date in this field must be equal to or before {0}",
    
/**
     * @cfg {String} invalidText
     * The error text to display when the date in the field is invalid (defaults to
     * '{value} is not a valid date - it must be in the format {format}').
     */
    invalidText : "{0} is not a valid date - it must be in the format {1}",
    
/**
     * @cfg {String} triggerClass
     * An additional CSS class used to style the trigger button.  The trigger will always get the
     * class 'x-form-trigger' and triggerClass will be appended if specified
     * (defaults to 'x-form-date-trigger' which displays a calendar icon).
     */
    triggerClass : 'x-form-date-trigger',
    
/**
     * @cfg {Boolean} showToday
     * false to hide the footer area of the DatePicker containing the Today button and disable
     * the keyboard handler for spacebar that selects the current date (defaults to true).
     */
    showToday : true,
    
/**
     * @cfg {Date/String} minValue
     * The minimum allowed date. Can be either a Javascript date object or a string date in a
     * valid format (defaults to null).
     */
    
/**
     * @cfg {Date/String} maxValue
     * The maximum allowed date. Can be either a Javascript date object or a string date in a
     * valid format (defaults to null).
     */
    
/**
     * @cfg {Array} disabledDays
     * An array of days to disable, 0 based (defaults to null). Some examples:


// disable Sunday and Saturday:
disabledDays:  [0, 6]
// disable weekdays:
disabledDays: [1,2,3,4,5]
     * 


     */
    
/**
     * @cfg {Array} disabledDates
     * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
     * expression so they are very powerful. Some examples:


// disable these exact dates:
disabledDates: ["03/08/2003", "09/16/2003"]
// disable these days for every year:
disabledDates: ["03/08", "09/16"]
// only match the beginning (useful if you are using short years):
disabledDates: ["^03/08"]
// disable every day in March 2006:
disabledDates: ["03/../2006"]
// disable every day in every March:
disabledDates: ["^03"]
     * 


     * Note that the format of the dates included in the array should exactly match the {@link #format} config.
     * In order to support regular expressions, if you are using a {@link #format date format} that has "." in
     * it, you will have to escape the dot when restricting dates. For example: ["03\\.08\\.03"].
     */
    
/**
     * @cfg {String/Object} autoCreate
     * A {@link Ext.DomHelper DomHelper element specification object}, or true for the default element
     * specification object:


     * autoCreate: {tag: "input", type: "text", size: "10", autocomplete: "off"}
     * 


     */

    // private
    defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},

    // in the absence of a time value, a default value of 12 noon will be used
    // (note: 12 noon was chosen because it steers well clear of all DST timezone changes)
    initTime: '12', // 24 hour format

    initTimeFormat: 'H',

    // PUBLIC -- to be documented
    safeParse : function(value, format) {
        if (/[gGhH]/.test(format.replace(/(\\.)/g, ''))) {
            // if parse format contains hour information, no DST adjustment is necessary
            return Date.parseDate(value, format);
        } else {
            // set time to 12 noon, then clear the time
            var parsedDate = Date.parseDate(value + ' ' + this.initTime, format + ' ' + this.initTimeFormat);
            
            if (parsedDate) return parsedDate.clearTime();
        }
    },

    initComponent : function(){
        Ext.form.DateField.superclass.initComponent.call(this);

        this.addEvents(
            
/**
             * @event select
             * Fires when a date is selected via the date picker.
             * @param {Ext.form.DateField} this
             * @param {Date} date The date that was selected
             */
            'select'
        );

        if(Ext.isString(this.minValue)){
            this.minValue = this.parseDate(this.minValue);
        }
        if(Ext.isString(this.maxValue)){
            this.maxValue = this.parseDate(this.maxValue);
        }
        this.disabledDatesRE = null;
        this.initDisabledDays();
    },

    initEvents: function() {
        Ext.form.DateField.superclass.initEvents.call(this);
        this.keyNav = new Ext.KeyNav(this.el, {
            "down": function(e) {
                this.onTriggerClick();
            },
            scope: this,
            forceKeyDown: true
        });
    },


    // private
    initDisabledDays : function(){
        if(this.disabledDates){
            var dd = this.disabledDates,
                len = dd.length - 1,
                re = "(?:";

            Ext.each(dd, function(d, i){
                re += Ext.isDate(d) ? '^' + Ext.escapeRe(d.dateFormat(this.format)) + '$' : dd[i];
                if(i != len){
                    re += '|';
                }
            }, this);
            this.disabledDatesRE = new RegExp(re + ')');
        }
    },

    
/**
     * Replaces any existing disabled dates with new values and refreshes the DatePicker.
     * @param {Array} disabledDates An array of date strings (see the {@link #disabledDates} config
     * for details on supported values) used to disable a pattern of dates.
     */
    setDisabledDates : function(dd){
        this.disabledDates = dd;
        this.initDisabledDays();
        if(this.menu){
            this.menu.picker.setDisabledDates(this.disabledDatesRE);
        }
    },

    
/**
     * Replaces any existing disabled days (by index, 0-6) with new values and refreshes the DatePicker.
     * @param {Array} disabledDays An array of disabled day indexes. See the {@link #disabledDays}
     * config for details on supported values.
     */
    setDisabledDays : function(dd){
        this.disabledDays = dd;
        if(this.menu){
            this.menu.picker.setDisabledDays(dd);
        }
    },

    
/**
     * Replaces any existing {@link #minValue} with the new value and refreshes the DatePicker.
     * @param {Date} value The minimum date that can be selected
     */
    setMinValue : function(dt){
        this.minValue = (Ext.isString(dt) ? this.parseDate(dt) : dt);
        if(this.menu){
            this.menu.picker.setMinDate(this.minValue);
        }
    },

    
/**
     * Replaces any existing {@link #maxValue} with the new value and refreshes the DatePicker.
     * @param {Date} value The maximum date that can be selected
     */
    setMaxValue : function(dt){
        this.maxValue = (Ext.isString(dt) ? this.parseDate(dt) : dt);
        if(this.menu){
            this.menu.picker.setMaxDate(this.maxValue);
        }
    },
    
    
/**
     * Runs all of NumberFields validations and returns an array of any errors. Note that this first
     * runs TextField's validations, so the returned array is an amalgamation of all field errors.
     * The additional validation checks are testing that the date format is valid, that the chosen
     * date is within the min and max date constraints set, that the date chosen is not in the disabledDates
     * regex and that the day chosed is not one of the disabledDays.
     * @param {Mixed} value The value to get errors for (defaults to the current field value)
     * @return {Array} All validation errors for this field
     */
    getErrors: function(value) {
        var errors = Ext.form.DateField.superclass.getErrors.apply(this, arguments);
        
        value = this.formatDate(value || this.processValue(this.getRawValue()));
        
        if (value.length < 1) { // if it's blank and textfield didn't flag it then it's valid
             return errors;
        }
        
        var svalue = value;
        value = this.parseDate(value);
        if (!value) {
            errors.push(String.format(this.invalidText, svalue, this.format));
            return errors;
        }
        
        var time = value.getTime();
        if (this.minValue && time < this.minValue.getTime()) {
            errors.push(String.format(this.minText, this.formatDate(this.minValue)));
        }
        
        if (this.maxValue && time > this.maxValue.getTime()) {
            errors.push(String.format(this.maxText, this.formatDate(this.maxValue)));
        }
        
        if (this.disabledDays) {
            var day = value.getDay();
            
            for(var i = 0; i < this.disabledDays.length; i++) {
                if (day === this.disabledDays[i]) {
                    errors.push(this.disabledDaysText);
                    break;
                }
            }
        }
        
        var fvalue = this.formatDate(value);
        if (this.disabledDatesRE && this.disabledDatesRE.test(fvalue)) {
            errors.push(String.format(this.disabledDatesText, fvalue));
        }
        
        return errors;
    },

    // private
    // Provides logic to override the default TriggerField.validateBlur which just returns true
    validateBlur : function(){
        return !this.menu || !this.menu.isVisible();
    },

    
/**
     * Returns the current date value of the date field.
     * @return {Date} The date value
     */
    getValue : function(){
        return this.parseDate(Ext.form.DateField.superclass.getValue.call(this)) || "";
    },

    
/**
     * Sets the value of the date field.  You can pass a date object or any string that can be
     * parsed into a valid date, using {@link #format} as the date format, according
     * to the same rules as {@link Date#parseDate} (the default format used is "m/d/Y").
     * 
Usage:
     * 


//All of these calls set the same date value (May 4, 2006)

//Pass a date object:
var dt = new Date('5/4/2006');
dateField.setValue(dt);

//Pass a date string (default format):
dateField.setValue('05/04/2006');

//Pass a date string (custom format):
dateField.format = 'Y-m-d';
dateField.setValue('2006-05-04');


     * @param {String/Date} date The date or valid date string
     * @return {Ext.form.Field} this
     */
    setValue : function(date){
        return Ext.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
    },

    // private
    parseDate : function(value) {
        if(!value || Ext.isDate(value)){
            return value;
        }

        var v = this.safeParse(value, this.format),
            af = this.altFormats,
            afa = this.altFormatsArray;

        if (!v && af) {
            afa = afa || af.split("|");

            for (var i = 0, len = afa.length; i < len && !v; i++) {
                v = this.safeParse(value, afa[i]);
            }
        }
        return v;
    },

    // private
    onDestroy : function(){
        Ext.destroy(this.menu, this.keyNav);
        Ext.form.DateField.superclass.onDestroy.call(this);
    },

    // private
    formatDate : function(date){
        return Ext.isDate(date) ? date.dateFormat(this.format) : date;
    },

    
/**
     * @method onTriggerClick
     * @hide
     */
    // private
    // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
    onTriggerClick : function(){
        if(this.disabled){
            return;
        }
        if(this.menu == null){
            this.menu = new Ext.menu.DateMenu({
                hideOnClick: false,
                focusOnSelect: false
            });
        }
        this.onFocus();
        Ext.apply(this.menu.picker,  {
            minDate : this.minValue,
            maxDate : this.maxValue,
            disabledDatesRE : this.disabledDatesRE,
            disabledDatesText : this.disabledDatesText,
            disabledDays : this.disabledDays,
            disabledDaysText : this.disabledDaysText,
            format : this.format,
            showToday : this.showToday,
            minText : String.format(this.minText, this.formatDate(this.minValue)),
            maxText : String.format(this.maxText, this.formatDate(this.maxValue))
        });
        this.menu.picker.setValue(this.getValue() || new Date());
        this.menu.show(this.el, "tl-bl?");
        this.menuEvents('on');
    },

    //private
    menuEvents: function(method){
        this.menu[method]('select', this.onSelect, this);
        this.menu[method]('hide', this.onMenuHide, this);
        this.menu[method]('show', this.onFocus, this);
    },

    onSelect: function(m, d){
        this.setValue(d);
        this.fireEvent('select', this, d);
        this.menu.hide();
    },

    onMenuHide: function(){
        this.focus(false, 60);
        this.menuEvents('un');
    },

    // private
    beforeBlur : function(){
        var v = this.parseDate(this.getRawValue());
        if(v){
            this.setValue(v);
        }
    }

    
/**
     * @cfg {Boolean} grow @hide
     */
    
/**
     * @cfg {Number} growMin @hide
     */
    
/**
     * @cfg {Number} growMax @hide
     */
    
/**
     * @hide
     * @method autoSize
     */
});
Ext.reg('datefield', Ext.form.DateField);





Ext.ns('App', 'App.control');


var mappanel = new App.control.mapPanel();

App.control.mapControl = Ext.extend(Ext.Panel, {
	// add tplMarkup as a new property
	tplMarkup: [
		'<img src={url} width="200", height="200"/><br/>',
		'<div id="btn-edit-map"></div>'
	],
	data: null,
	onEdit: function(btn, e){
		Ext.MessageBox.alert('Data', this.name)
	},
	// startingMarup as a new property
	startingMarkup: 'Loading map...',
	// override initComponent to create and compile the template
	// apply styles to the body of the panel and initialize
	// html to startingMarkup
	initComponent: function() {
		this.tpl = new Ext.Template(this.tplMarkup);
		Ext.apply(this, {
//			bodyStyle: {
//				background: '#ffffff',
//				padding: '7px'
//			},
			width: 205,
			height: 250,
			frame: true,
			html: this.startingMarkup
		});
		// call the superclass's initComponent implementation
		App.control.mapControl.superclass.initComponent.call(this);
	},
	// add a method which updates the details
	updateControl: function(data) {
		this.data = data;
		//generate a google static map url
		var url;
		var path = []
		var x = data.polygon;//geojson format, //x = {"type":"Polygon","coordinates":[[[-83.020916781754,40.002161106657],[-83.020648560853,40.002621341393],[-83.020208678574,40.002950078591],[-83.019741974205,40.003073354632],[-83.018846116395,40.002908986528],[-83.018374047608,40.002013173405],[-83.018910489412,40.000426980057],[-83.01995118651,40.000381777115],[-83.021024070116,40.000681759709],[-83.020916781754,40.002161106657]]]};
		for (var i=0; i<x.coordinates[0].length; i++){
			var xy = x.coordinates[0][i];
			path.push([xy[1] + ',' + xy[0]])
		}
		
		var path_str = path.join('|');
		
		var pt = data.center; //array [x, y]
		
		url = 'http://maps.google.com/maps/api/staticmap?size=200x200&path=fillcolor:0xAA000033|color:0xFFFFFF00|' + path_str + '&sensor=false&markers=color:blue|' + pt[0] + ',' + pt[1];
		
		data = {url: url};
		
		this.tpl.overwrite(this.body, data);
		var s = this;
		var fn = this.onEdit;
		var btn = new Ext.Button({
			text: 'Edit',
			minWidth: '200',
			renderTo: 'btn-edit-map',
			handler: fn,
			scope: s
		}
		)
		
	}
});
// register the App.BookDetail class with an xtype of bookdetail
Ext.reg('app_mapcontrol', App.control.mapControl);


App.control.mapField = Ext.extend(Ext.Window, {
	map: null,
	featureLayer: null,
	onCancel: function(btn, e){
		this.hide()
	},
	onOK: function(btn, e){
		
		//check if only one polygon is drawn		
		if (vector.features.length>1) {
			actions["edit"].control.deactivate();
			actions["drawpolygon"].control.deactivate();
			Ext.MessageBox.alert('Warning', 'Only one polygon is allowed.');
			return
		} else if  (vector.features.length==0) {
			Ext.MessageBox.alert('Warning', 'No polyon was drawn.');
			return
		}
		
		//save the geometry in the field
		var geojson_format = new OpenLayers.Format.GeoJSON();
		//transform the geometry
		var geom = vector.features[0].geometry.clone().transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326")); 

		this.form.getForm().findField('project').setValue(geojson_format.write(geom));
		this.hide()	
		
	},
	clearFeatures: function(){
		var polygonLayer = this.polygonLayer;
		var pointLayer = this.polylineLayer;	
	},
	
    initComponent: function(){
        var config = {
			modal: true,
			maximizable: true,
			layout: 'fit', //in IE it wouldn't draw the panel correctly if this is not specifically defined.
            items: {
				xtype: 'mappanel',
				id: 'app-mappanel'
			},
			closeAction: 'hide'
			,buttons: [{
				text: 'OK',
				handler: this.onOK,
				scope: this
			}, {
				text: 'Cancel',
				handler: this.onCancel,
				scope: this
			}]
        }; // eo config object
        // apply config
		
		
        Ext.apply(this, Ext.apply(this.initialConfig, config));
        
        App.control.mapField.superclass.initComponent.apply(this, arguments);
    } // eo function initComponent
//    ,onRender: function(){
//        this.store.load();
//        
//        App.control.mapField.superclass.onRender.apply(this, arguments);
//    } // eo function onRender
});

Ext.reg('mapfield', App.control.mapField);


